package com.yanze.schoolinformation.view.information.book;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v4.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.example.xrecyclerview.XRecyclerView;
import com.yanze.schoolinformation.R;
import com.yanze.schoolinformation.adapter.rv.BookListAdapter;
import com.yanze.schoolinformation.base.BaseActivity;
import com.yanze.schoolinformation.databinding.ActivityBookListBinding;
import com.yanze.schoolinformation.databinding.HeaderItemBookBinding;
import com.yanze.schoolinformation.app.C;
import com.yanze.schoolinformation.model.bean.book.BookBean;
import com.yanze.schoolinformation.model.http.DeforObserver;
import com.yanze.schoolinformation.model.http.reqo.DataReqo;
import com.yanze.schoolinformation.utils.CommonUtils;

import io.reactivex.disposables.Disposable;

public class BookListActivity extends BaseActivity<ActivityBookListBinding> {
    private static final String TYPE = "param1";
    private String mType = "综合";

    // 开始请求的角标
    private int mStart = 0;
    // 一次请求的数量
    private int mCount = 18;
    private BookListAdapter mBookAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list);
        setTitle("书籍");
        if (getIntent() != null) {
            mType = getIntent().getStringExtra(TYPE);
        }

        showContentView();
        initRefreshView();

        loadData();
    }

    private void initRefreshView() {
        bindingView.srlBook.setColorSchemeColors(CommonUtils.getColor(R.color.colorTheme));
        bindingView.srlBook.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                bindingView.srlBook.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mStart = 0;
                        bindingView.xrvBook.reset();
                        loadCustomData();
                    }
                }, 1000);
            }
        });
        bindingView.xrvBook.setLayoutManager(new GridLayoutManager(this, 3));
        bindingView.xrvBook.setPullRefreshEnabled(false);
        bindingView.xrvBook.clearHeader();
        mBookAdapter = new BookListAdapter(this);
        bindingView.xrvBook.setAdapter(mBookAdapter);
        final HeaderItemBookBinding oneBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.header_item_book, null, false);
        bindingView.xrvBook.addHeaderView(oneBinding.getRoot());
        oneBinding.etTypeName.setText(mType);
        oneBinding.etTypeName.setSelection(mType.length());
        /** 处理键盘搜索键 */
        oneBinding.etTypeName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mStart = 0;
                    bindingView.xrvBook.reset();
                    String tag = oneBinding.etTypeName.getText().toString().trim();
                    if (tag.equals("")) {
                        mType = "全部";
                    } else {
                        mType = oneBinding.etTypeName.getText().toString().trim();
                    }
                    loadCustomData();
                }
                return false;
            }
        });
        bindingView.xrvBook.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {
                mStart += mCount;
                loadCustomData();
            }
        });
    }

    private void loadData() {
        bindingView.srlBook.setRefreshing(true);
        bindingView.srlBook.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadCustomData();
            }
        }, 500);
    }

    //请求网络
    private void loadCustomData() {
        DataReqo.getInstant().getBookByTag(C.url.API_DOUBAN, mType, mStart, mCount)
                .subscribe(new DeforObserver<BookBean>() {
                    @Override
                    public void _onSubscribe(Disposable disposable) {
                        addSubscription(disposable);
                    }

                    @Override
                    public void _onNext(BookBean entity) {
                        if (mStart == 0) {
                            if (entity != null && entity.getBooks() != null && entity.getBooks().size() > 0) {
                                mBookAdapter.clear();
                                mBookAdapter.addAll(entity.getBooks());
                                mBookAdapter.notifyDataSetChanged();
                                bindingView.xrvBook.refreshComplete();
                            }
                        } else {
                            if (entity != null
                                    && entity.getBooks() != null
                                    && entity.getBooks().size() > 0) {
                                bindingView.xrvBook.refreshComplete();
                                mBookAdapter.addAll(entity.getBooks());
                                mBookAdapter.notifyDataSetChanged();
                            } else {
                                bindingView.xrvBook.noMoreLoading();
                            }
                        }
                    }

                    @Override
                    public void _onError(String msg) {
                        showContentView();
                        if (bindingView.srlBook.isRefreshing()) {
                            bindingView.srlBook.setRefreshing(false);
                        }
                        if (mStart == 0) {
                            showError();
                        } else {
                            bindingView.xrvBook.refreshComplete();
                        }
                    }

                    @Override
                    public void onComplete() {
                        showContentView();
                        if (bindingView.srlBook.isRefreshing()) {
                            bindingView.srlBook.setRefreshing(false);
                        }
                    }
                });
    }

    /**
     * 失败后点击刷新
     */
    protected void onRefresh() {
        bindingView.srlBook.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadCustomData();
            }
        }, 500);
    }

    /**
     * 入口
     */
    public static void start(Context context, String type) {
        Intent intent = new Intent(context, BookListActivity.class);
        intent.putExtra(TYPE, type);
        context.startActivity(intent);
    }
}
